<template>
  <el-row style="padding: 5px">
    <el-row>
      <el-card>
        <el-form :inline="true" :model="batchParams" class="" size="small">
          <el-form-item label="种质名称">
            <el-select placeholder="请选择种质" v-model="batchParams.germplasmId">
              <el-option v-for="item in germplasmOptions"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="种植时间">
            <el-date-picker
              v-model="dateValue1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="收获时间">
            <el-date-picker
              v-model="dateValue2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="selectTBatchData">搜索</el-button>
            <el-button type="" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button
              type="primary" plain icon="el-icon-plus" @click="addTBatchData(1) "  v-hasPermi="['agriculture:batch:add']">新增</el-button>
            <el-button type="warning" plain icon="el-icon-download">导出</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
    <el-row style="margin-top: 5px">
      <el-card>
        <el-table :data="tableData.slice((currentPage -1) *pageSize,currentPage*pageSize)" border style="width: 100%">
          <el-table-column fixed align="center" prop="batchCode" label="批次号" ></el-table-column>
          <el-table-column align="center" prop="germplasmName" label="种质" ></el-table-column>
          <el-table-column align="center" prop="quantity" label="产量" ></el-table-column>
          <el-table-column align="center" prop="seed" label="种苗信息"  width="180"></el-table-column>
          <el-table-column align="center" prop="createDate" label="种植时间" ></el-table-column>
          <el-table-column align="center" prop="harvestDate" label="收获时间" width="120" ></el-table-column>
          <el-table-column align="center" prop="landName" label=地块 ></el-table-column>
          <el-table-column align="center" label="操作" width="310"  fixed="right">
            <template slot-scope="scope" >
              <el-button type="warning" class="mini_Button" icon="el-icon-edit" @click="updateTBatchData(scope.row,1)" v-hasPermi="['agriculture:batch:update']">修改</el-button>
              <el-button type="danger" class="mini_Button" icon="el-icon-delete" @click="deleteTBatchData(scope.row.batchId)" v-hasPermi="['agriculture:batch:del']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin: 20px 0; float: right"
          :current-page.sync="currentPage"
          background
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="this.tableData.length">
        </el-pagination>
      </el-card>
    </el-row>

    <el-dialog  :visible.sync="this.dialog" width="30%">
      <template v-slot:title>
        <div style="color: black;font-weight:1000; font-size: 20px;">{{dialogTitle}}</div>
      </template>
      <el-form :model="this.addTBatch">
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>批次编号</template>
          <el-input v-model="addTBatch.batchCode" autocomplete="off" placeholder="请选择批次编号" style="width:70%"></el-input>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>种质选择</template>
          <el-select v-model="addTBatch.germplasmId" placeholder="请选择种质" style="width:70%">
            <el-option v-for="item in germplasmOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;opacity:0; "></i>产品产量</template>
          <el-input v-model="addTBatch.quantity" autocomplete="off" placeholder="请输入产品产量" style="width:70%"></el-input>
        </el-form-item>
        <el-form-item :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>种植时间</template>
          <el-date-picker
            v-model="addTBatch.createDate"
            type="date"
            placeholder="选择日期时间"
            style="width:70%">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;opacity:0;; "></i>收获时间</template>
          <el-date-picker
            v-model="addTBatch.harvestDate"
            type="date"
            placeholder="选择日期时间"
            style="width:70%">
          </el-date-picker>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ; opacity:0; "></i>种苗信息</template>
          <el-input v-model="addTBatch.seed" type="textarea" autocomplete="off"  placeholder="请输入种苗信息" style="width:70%" rows="=2" ></el-input>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>所属地块</template>
          <el-select v-model="addTBatch.landId" autocomplete="off" placeholder="请选择所属地块" style="width:70%">
            <el-option v-for="item in landOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog=false">取 消</el-button>
        <el-button type="primary" @click="handleButtonClick">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>
<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Template from "@/views/iot/template/index.vue";
import Button_disbable from "@/views/agriculture/buttonDis/button_disbable.vue";
import {addTBatch, delTBatch, listTBatch, updateTBatch} from "@/api/agriculture/tbatch";
import {listGermplasm} from "@/api/agriculture/germplasm.js"
import {listLand} from "@/api/agriculture/land";


export default {
  components: {Button_disbable, Template},
  data() {
    const initialAddData={
      germplasmId:'',
      batchCode:'',
      seed:'',
      quantity:'',
      createDate:'',
      harvestDate:'',
      landId:''
    }
    return {
      pickerOptions:{
        shortcuts:[],
      },
      dateValue1:'',
      dateValue2:'',
      addTBatch:{...initialAddData},
      initialAddData,
      dialog:false,
      dialogTitle:'',
      currentPage:1,
      pageSize:10,
      switch:true,
      switch2:false,
      germplasmParams:{
        germplasmId:''
      },
      batchParams:{
        batchId:'',
        germplasmId:'',
        batchCode:'',
        quantity:'',
        seed:'',
        params:{
          beginCreateDate:'',
          endCreateDate:'',
          beginHarvestDate:'',
          endinHarvestDate:''
        },
        landId:'',
      },
      formInline: {
        product:'',
        region: ''
      },
      landOptions:'',
      germplasmOptions:'',
      tableData:[],
      addOrUpdate:'',
      requiredFields :{  batchCode:'请输入批次编号！' ,germplasmId:'请选择种质！', createDate:'请选择种植日期！',landId:'请选择地块！' }
    }
  },
  async mounted() {
    await this.getTBatchList()
     this.pickerData()
  },
  methods:{
   async getLandList()
    {
      const row = await listLand();
      this.landOptions =row.rows.map(item =>({
        label:item.landName,
        value:item.landId
      }))

    },
    pickerData()
    {
      this.pickerOptions.shortcuts = [{
        text: '最近一周',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近一个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近三个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          picker.$emit('pick', [start, end]);
        }
      }]
    },
    // 化时间日期
    changeTime(originalDateString){
      const originalDate = new Date(Date.parse(originalDateString));
      const year = originalDate.getFullYear();
      const month = String(originalDate.getMonth() + 1).padStart(2, '0');
      const day = String(originalDate.getDate()).padStart(2, '0');
      const hours = String(originalDate.getHours()).padStart(2, '0');
      const formattedDateString = `${year}-${month}-${day}`;
      return formattedDateString;
    },
    // 对话框确定按钮选择监听修改或新增
    handleButtonClick() {
      if (this.addOrUpdate === 1) {
        this.updateTBatchData(this.addTBatch.row,2)
      } else {
        this.addTBatchData(2);
      }
    },
      async getTBatchList()
      {
        const row = await listTBatch(this.batchParams)
        const row1 = await listGermplasm(this.germplasmParams)
        const  row2 = await listLand()
        this.germplasmOptions = row1.rows.map(item1 =>({
          value:item1.germplasmId,
          label:item1.germplasmName,
        }))
        this.tableData =row.rows.map(item1=>{
          const findData =row1.rows.find(item2 => item1.germplasmId === item2.germplasmId)
          const findData2 =row2.rows.find(item3 => item1.landId === item3.landId)
          return {
            ...item1,
            germplasmName:findData.germplasmName,
            landName:findData2.landName
          }
        })
      },
    // 警告消息
    openMessage(type,mes) {
      this.$notify({
        title: '提示',
        message: mes,
        offset: 30,
        type: type
      });
    },
    // 添加批次
    async addTBatchData(buttonId)
    {
      if(buttonId == 1) {this.addTBatch = {...this.initialAddData};this.dialogTitle ='添加批次';this.dialog= true; this.addOrUpdate = 0;this.getLandList()}
      else if(buttonId == 2) {
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addTBatch[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
        try {
          await addTBatch(this.addTBatch)
          this.openMessage('success', '添加成功！');
          await this.getTBatchList()
          this.dialog = false
        } catch (error) {
          console.error('添加溯源批次错误:', error);
          this.openMessage('error', '添加失败！');
        }
      }
    },
    // 修改溯源版本
    async updateTBatchData(row,buttonId)
    {
      if(buttonId == 1) {this.addTBatch= {...row} ;this.dialogTitle ='修改批次版本';this.dialog=true;this.addOrUpdate = 1;this.getLandList() }
      else if(buttonId == 2){
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addTBatch[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
        try {
          await updateTBatch(this.addTBatch)
          this.openMessage('success', '修改成功！');
          await this.getTBatchList()
          this.dialog = false
        }catch (error){
          console.error('Error occurred while update sellpro:', error);
          this.openMessage('error', '修改失败！');
        }
      }
    },
    // 查询
    async selectTBatchData()
    {
      if(this.dateValue1)
      {
        this.batchParams.params.beginCreateDate = this.changeTime(this.dateValue1[0])
        this.batchParams.params.endCreateDate = this.changeTime(this.dateValue1[1])
      }
      if(this.dateValue2)
      {
        this.batchParams.params.beginHarvestDate = this.changeTime(this.dateValue2[0])
        this.batchParams.params.endinHarvestDate = this.changeTime(this.dateValue2[1])
      }
      await this.getTBatchList()
    },
    // 重置
    resetForm()
    {
      this.batchParams.germplasmId=''
      this.batchParams.params.beginCreateDate=''
      this.batchParams.params.endCreateDate=''
      this.batchParams.params.beginHarvestDate=''
      this.batchParams.params.endinHarvestDate=''
      this.getTBatchList()
    },
    // 删除批次
   async deleteTBatchData(id)
    {
      this.$confirm('确认删除？')
        .then(async _ => {
          try {
            delTBatch(id)
            this.openMessage('success', '删除成功！');
            await this.getTBatchList()
          } catch (error) {
            console.log("溯源批次删除错误:", error)
            this.openMessage('error', '删除失败！');
          }
        }).catch(_ => {
        return
      });
    }
  },
}
</script>
<style scoped>
.mini_Button{
  font-size:11px;
  padding: 3px 5px
}
</style>

